# -*- coding: utf-8 -*-

from socket import *
import struct
import json
from rest_framework.response import Response
from rest_framework import status as status_code

def is_valid(request, method, *args, **kwargs):
    """
    获取request中的表单数据，验证数据无误返回一个字典，如果有异常数据会返回一个Response对象
    调用格式如：is_valid(request, "POST", "uid", username=None, role=None)
    :param request:
    :param method:
    :param kwargs:
    :return:
    """
    keys = list(args) + list(kwargs.keys())
    for key in keys:                                # 设置第一种获取方式（获取Form表单格式数据）
        if method == "GET":
            value = request.GET.get(key, None)
        elif method == "POST":
            value = request.POST.get(key, None)
            print(1)
        elif method == "PUT":
            value = request.PUT.get(key, None)

        if not value:                               # 设置第二种获取方式（获取转为JSON的数据格式）
            value = request.data[key]
            print(2)
        if not value:                               # 为空则返回
            return Response({"message": "Parameter '%s' cannot be empty!" % key},
                            status=status_code.HTTP_400_BAD_REQUEST)
        else:
            kwargs[key] = value
    return kwargs


def receive():
    try:
        ADDR = ('127.0.0.1',8000)
        BUFSIZE = 1024

        FILEINFO_SIZE=struct.calcsize('128s32sI8s')

        recvSock = socket(AF_INET,SOCK_STREAM)

        recvSock.bind(ADDR)

        recvSock.listen(True)

        # print("等待连接...")

        conn,addr = recvSock.accept()

        # print("客户端已连接—> ")

        fhead = conn.recv(FILEINFO_SIZE)

        filename,temp1,filesize,temp2=struct.unpack('128s32sI8s',fhead)

        #print filename,temp1,filesize,temp2

        # print(filename,len(filename),type(filename))
        #
        # print(filesize)
        # print(filename.decode('utf-8'))
        filename = filename.decode('utf-8').strip('\00') #...
        # print(filename)
        fp = open('D:/ku'+filename, 'wb')
        restsize = filesize
        # print("正在接收文件... ",)
        while 1:
            if restsize > BUFSIZE:
                filedata = conn.recv(BUFSIZE)
            else:
                filedata = conn.recv(restsize)
            if not filedata: break
            fp.write(filedata)
            restsize = restsize-len(filedata)
            if restsize == 0: break

        # print("接收文件完毕，正在断开连接...")

        fp.close()
        conn.close()
        recvSock.close()
    except Exception as e:
        filename = ''

    # print("连接已关闭...")
    return filename
if __name__ == '__main__':
    print(receive())
